package diona.search

import net.liftweb.squerylrecord.KeyedRecord
import org.squeryl.annotations._
import net.liftweb.record.{MetaRecord, Record}
import net.liftweb.squerylrecord.RecordTypeMode._
import diona.model.{User, PublisherSchema}
import java.util.Calendar
import net.liftweb.record.field._

/**
 * User: anton
 * Date: 03.07.11 14:01
 */
class SearchResult extends Record[SearchResult] with KeyedRecord[Long]
{
  override def meta = SearchResult

  @Column(name = "id")
  override val idField = new LongField(this)

  val date = new DateTimeField(this)
  val itemsFound = new IntField(this, 0)

  val searchType = new EnumField(this, SearchType)

  val requestId = new LongField(this)
}

object SearchResult extends SearchResult with MetaRecord[SearchResult]
{
  private lazy val t = PublisherSchema.searchResults;

  @volatile var create: (String, Int, User) => SearchResult =
    (query, itemsFound, user) => {
      inTransaction {
        val request = SearchRequest.getOrCreateByQuery(user, query)
        val result = SearchResult.createRecord
          .date(Calendar.getInstance)
          .itemsFound(itemsFound)
          .requestId(request.id)
        t.insert(result)
      }
    }

  @volatile var createForTask: (SearchTask, Int) => SearchResult =
    (task, itemsFound) => {
      inTransaction {
        val result = SearchResult.createRecord
          .date(Calendar.getInstance)
          .itemsFound(itemsFound)
          .searchType(task.searchType.is)
          .requestId(task.requestId.is)
        t.insert(result)
      }
    }
}